#include "updateque.h"
#include "ui_updateque.h"

Updateque::Updateque(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Updateque)
{
    ui->setupUi(this);
    this->setWindowTitle("修改试题");
    db = Database::getInstance().getDatabase();
}

Updateque::~Updateque()
{
    delete ui;
}

void Updateque::on_pushButton_upd_refersh_clicked()
{
    QString sql = "select * from questions";
    QSqlQuery query(db);
    if(!query.exec(sql))
        QMessageBox::information(this,"查看","Error"+db.lastError().text());
    int line_count = ui->tableWidget->rowCount();
    //清空表格
    for(int i=0;i<line_count;i++)
        ui->tableWidget->removeRow(0);
    while(query.next())
    {
        qDebug() << query.value(0).toString() << query.value(1).toString();
        ui->tableWidget->insertRow(0);//插入0行
        QTableWidgetItem *item0 = new QTableWidgetItem(query.value(0).toString());
        QTableWidgetItem *item1 = new QTableWidgetItem(query.value(1).toString());
        QTableWidgetItem *item2 = new QTableWidgetItem(query.value(2).toString());
        ui->tableWidget->setItem(0,0,item0);
        ui->tableWidget->setItem(0,1,item1);//设置item
        ui->tableWidget->setItem(0,2,item2);
    }
}

void Updateque::on_pushButton_upd_exit_clicked()
{
    this->close();
    emit upd_exit();
}

void Updateque::on_pushButton_upd_conf_clicked()
{
    int id = ui->lineEdit_que_id->text().toInt();
    QString text = ui->textEdit->toPlainText();
    QString optionA = ui->lineEdit_A->text().trimmed();
    QString optionB = ui->lineEdit_B->text().trimmed();
    QString optionC = ui->lineEdit_C->text().trimmed();
    QString optionD = ui->lineEdit_D->text().trimmed();

    if (text.isEmpty() || optionA.isEmpty() || optionB.isEmpty() || optionC.isEmpty() || optionD.isEmpty()) {
        QMessageBox::warning(this, "update Error", "Please fill in all fields.");
        return;
    }

    QString options = optionA + "|" + optionB + "|" + optionC + "|" + optionD;

    question newQuestion(id,text, options);
    question Myquestion(0,"","");

    if (Myquestion.updateQuestion(newQuestion)) {
        QMessageBox::information(this, "Success", "Question update successfully!");
        //this->close();
    } else {
        QMessageBox::critical(this, "Error", "Failed to update question.");
    }

}
